package com.sdksoft.readcard

import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import cn.mtjsoft.ocr_android.ScanningManager
import cn.mtjsoft.ocr_android.config.Config
import cn.mtjsoft.ocr_android.enums.ScanTypeEnum
import cn.mtjsoft.ocr_android.interfaces.ScanResultListener
import com.csht.autograde.CshtMqttService
import com.csht.cache.SpManager
import com.csht.encryption.md5.MD5Util
import com.csht.encryption.sm4.SM4Util
import com.csht.extentions.RxLifeScope
import com.csht.utils.BoardCastUtils
import com.csht.utils.BytesUtils
import com.csht.utils.HHTipUtils
import com.csht.utils.JsonUtils
import com.csht.utils.LogUtils
import com.sdksoft.readcard.bean.OCRRequestParam
import com.sdksoft.readcard.databinding.ActivityReadTypeBinding
import com.sdksoft.readcard.testConfig.TestConfigActivity
import com.sdksoft.readcard.utils.ImgUtils
import com.sdksoft.readcard.utils.NetworkManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.nio.ByteBuffer

class ChooseTypeActivity : BaseInitActivity() {

    private lateinit var activityReadTypeBinding: ActivityReadTypeBinding

    private var imageUri: Uri? = null
    private var ocrType = ScanTypeEnum.IDCARD_FRONT

    override fun onResume() {
        super.onResume()
        stopService(Intent(this, CshtMqttService::class.java))
        BoardCastUtils.unRegistUsb(this)
    }

    override fun initView() {
        super.initView()
        Log.e("ChooseTypeActivity", "ChooseTypeActivity onCreate")
        setTitleText(getString(R.string.app_name), false)
        ByteBuffer.wrap(ByteArray(0))
        activityReadTypeBinding =
            ActivityReadTypeBinding.inflate(layoutInflater, baseActivityBinding.llContent, false)
        baseActivityBinding.llContent.apply {
            addView(activityReadTypeBinding.root, 0)
        }
        activityReadTypeBinding.apply {
//            if (hasNFC(baseContext)) {
//                typeNfc.visibility = View.VISIBLE
//                typePassport.visibility = View.VISIBLE
//                typeForeign.visibility = View.GONE
//            } else {
//                typeNfc.visibility = View.GONE
//                typePassport.visibility = View.GONE
//                typeForeign.visibility = View.GONE
//            }
            typeNfc.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        NFCActivity::class.java
                    )
                )
            }
            typeNfcTag.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        NFCTAGActivity::class.java
                    )
                )
            }
            typePassport.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        NFCHuZhaoActivity::class.java
                    )
                )
            }
            typeForeign.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        NFCYJZActivity::class.java
                    )
                )
            }
            typeNfcBank.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        NFCBankCardActivity::class.java
                    )
                )
            }
            typeOCRIdcard.setOnClickListener {
                ocrType = ScanTypeEnum.IDCARD_FRONT
                openCamera()
//                ScanningManager.instance.openScanningActivity(
//                    this@ChooseTypeActivity,
//                    Config(
//                        scanType = ScanTypeEnum.IDCARD_FRONT,
//                        scanResultListener = object : ScanResultListener {
//                            override fun onSuccessListener(value: String?, bitmap: Bitmap?) {
//                                startActivity(
//                                    Intent(
//                                        this@ChooseTypeActivity,
//                                        OCRIDCardActivity::class.java
//                                    ).apply {
//                                        putExtra("value", value)
//                                    }
//                                )
//                            }
//
//                            override fun onFailureListener(error: String) {
//                                HHTipUtils.getInstance().showToast(this@ChooseTypeActivity, error)
//                            }
//                        })
//                )
            }
            typeOCRIdcardBack.setOnClickListener {
                ocrType = ScanTypeEnum.IDCARD_BACK
                openCamera()
//                ScanningManager.instance.openScanningActivity(
//                    this@ChooseTypeActivity,
//                    Config(
//                        scanType = ScanTypeEnum.IDCARD_BACK,
//                        scanResultListener = object : ScanResultListener {
//                            override fun onSuccessListener(value: String?, bitmap: Bitmap?) {
//                                startActivity(
//                                    Intent(
//                                        this@ChooseTypeActivity,
//                                        OCRIDCardActivity::class.java
//                                    ).apply {
//                                        putExtra("value", value)
//                                    }
//                                )
//                            }
//
//                            override fun onFailureListener(error: String) {
//                                HHTipUtils.getInstance().showToast(this@ChooseTypeActivity, error)
//                            }
//                        })
//                )
            }

            typeOCRBank.setOnClickListener {
                ScanningManager.instance.openScanningActivity(
                    this@ChooseTypeActivity,
                    Config(
                        scanType = ScanTypeEnum.BANK_CARD_NUMBER,
                        scanResultListener = object : ScanResultListener {
                            override fun onSuccessListener(value: String?, bitmap: Bitmap?) {
                                startActivity(
                                    Intent(
                                        this@ChooseTypeActivity,
                                        OCRIDCardActivity::class.java
                                    ).apply {
                                        putExtra("value", value)
                                    }
                                )
                            }

                            override fun onFailureListener(error: String) {
                                HHTipUtils.getInstance().showToast(this@ChooseTypeActivity, error)
                            }
                        })
                )
            }

            typeUsb.setOnClickListener { v: View? ->
                val intent = Intent(this@ChooseTypeActivity, UsbActivity::class.java)
                intent.putExtra("readType", "0")
                startActivity(intent)
            }
            typeUsbXzkj.setOnClickListener { v: View? ->
                val intent = Intent(this@ChooseTypeActivity, UsbActivity::class.java)
                intent.putExtra("readType", "1")
                startActivity(intent)
            }

            typeUsbDk.setOnClickListener { v: View? ->
                val intent = Intent(this@ChooseTypeActivity, UsbActivity::class.java)
                intent.putExtra("readType", "2")
                startActivity(intent)
            }

            typeUsbApdu.setOnClickListener { v: View? ->
                val intent = Intent(this@ChooseTypeActivity, UsbActivity::class.java)
                intent.putExtra("readType", "3")
                startActivity(intent)
            }

            typePort.setOnClickListener { v: View? ->
                val intent = Intent(this@ChooseTypeActivity, PortActivity::class.java)
                intent.putExtra("readType", "1")
                startActivity(intent)
            }
            typePortDkPassport.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        PassportHuZhaoActivity::class.java
                    ).apply {
                        putExtra("type", 0)
                    }
                )
            }
            typeUsbDkPassport.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        PassportHuZhaoActivity::class.java
                    ).apply {
                        putExtra("type", 1)
                    }
                )
            }
            typeUsbPassport.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        PassportHuZhaoActivity::class.java
                    ).apply {
                        putExtra("type", 2)
                    }
                )
            }
            typePortDk.setOnClickListener { v: View? ->
                val intent = Intent(this@ChooseTypeActivity, PortActivity::class.java)
                intent.putExtra("readType", "2")
                startActivity(intent)
            }
            typeSam.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        SamActivity::class.java
                    )
                )
            }
            typeSamMulti.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        SamMultiActivity::class.java
                    )
                )
            }
            typeBle.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        Ble2Activity::class.java
                    ).apply {
                        putExtra("bleType", 0)
                    }
                )
            }
            typeBleZgbj.setOnClickListener { v: View? ->
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        Ble2Activity::class.java
                    ).apply {
                        putExtra("bleType", 1)
                    }
                )
            }
            typeM1.setOnClickListener { v: View? ->
                val intent = Intent(this@ChooseTypeActivity, UsbM1Activity::class.java)
                startActivity(intent)
            }
            tvConfig.setOnClickListener {
                startActivity(
                    Intent(
                        this@ChooseTypeActivity,
                        TestConfigActivity::class.java
                    )
                )
            }
            typeOCRBank.visibility = View.GONE
//            typeOCRIdcard.visibility = View.GONE
//            typeOCRIdcardBack.visibility = View.GONE

//            typePassport.visibility = View.GONE  // NFC护照/通行证
//            typeNfcBank.visibility = View.GONE   // NFC银行卡
//            typeForeign.visibility = View.GONE    // NFC外国居住证
//            typeUsb.visibility = View.GONE
//            typePort.visibility = View.GONE

//            typeUsbXzkj.visibility = View.GONE

//            typeUsbDk.visibility = View.GONE
//            typeUsbDkPassport.visibility = View.GONE
//            typePortDk.visibility = View.GONE
//            typePortDkPassport.visibility = View.GONE

//            typeSam.visibility = View.GONE
//            typeBle.visibility = View.GONE
//            tvConfig.visibility = View.GONE
        }
        AlertDialog.Builder(this)
            .setTitle("温馨提示")
            .setMessage("测试使用的appid不可用于商业用途，商用appid请务必联系我司商务进行分配")
            .setCancelable(false)
            .setPositiveButton("确定") { dialog: DialogInterface, which: Int -> dialog.dismiss() }
            .show()
        // 测试
        val source = "what are you doing"
        LogUtils.e("SM4: ", "明文 ：$source")
        val key = "FUARZKHAYCGY9PTM".toByteArray()
        val keyHex = BytesUtils.bytesToHexString(key)
        LogUtils.e("SM4: ", "keyHex ：$keyHex")

        val dataE = SM4Util.encryptECB(source.toByteArray(), key)
        LogUtils.e("SM4: ", "SM4_ECB_PKCS5 密文 ：${BytesUtils.bytesToHexString(dataE)}")
        LogUtils.e("SM4: ", "SM4_ECB_PKCS5 解密 ：${String(SM4Util.decryptECB(dataE, key))}")
    }

    private fun openCamera() {
        val intent = Intent()
        // 指定开启系统相机的Action
        intent.action = MediaStore.ACTION_IMAGE_CAPTURE
        intent.addCategory(Intent.CATEGORY_DEFAULT)
        // 根据文件地址创建文件
        val file = File(baseContext.getExternalFilesDir("")?.absolutePath + "/ocr.jpg")
        if (file.exists()) {
            file.delete()
        }
        // 把文件地址转换成Uri格式
        imageUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            /*7.0以上要通过FileProvider将File转化为Uri*/
            file.let {
                FileProvider.getUriForFile(baseContext, "$packageName.fileprovider", it)
            }
        } else {
            /*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
            Uri.fromFile(file)
        }
        // 设置系统相机拍摄照片完成后图片文件的存放地址
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        startActivityForResult(intent, 100)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //拍照的结果
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            val file = File(baseContext.getExternalFilesDir("")?.absolutePath + "/ocr.jpg")
            if (!file.exists()) {
                HHTipUtils.getInstance().showToast(baseContext, "照片不存在")
                return
            }
            RxLifeScope().launch({
                HHTipUtils.getInstance().showProgressDialog(baseContext, "识别中...")
                val ocrRequestParam = withContext(Dispatchers.IO) {
                    // 压缩转换base64照片
                    val saveFile = File(baseContext.getExternalFilesDir("")?.absolutePath + "/ocr_CompressQuality.jpg")
                    val base64 =
                        ImgUtils.getBase64ImgCompressQuality(
                            file.absolutePath,
                            false,
                            500,
                            500,
                            500,
                            saveFile
                        )
                    // 网络识别
                    val timestampString = System.currentTimeMillis().toString()
                    OCRRequestParam().apply {
                        appId = SpManager.appid
                        appKey = "xkgZRIxC0l8CPRJx"
                        timestamp = timestampString
                        sign = MD5Util.stringMD5("${appId}${appKey}${timestamp}AaAvZ4rCEd94aYEx")
                        img = base64
                    }
                }
                when (ocrType) {
                    ScanTypeEnum.IDCARD_FRONT -> {
                        ocrRequestParam.type = 4
                        val result = NetworkManager.init.userService().ocrIDCardFrontRequest(ocrRequestParam)
                        LogUtils.i("识别结果", result.data)
                        if (result.isSuccess()) {
                            startActivity(
                                Intent(
                                    this@ChooseTypeActivity,
                                    OCRIDCardActivity::class.java
                                ).apply {
                                    putExtra("value", JsonUtils.gson.toJson(result.data))
                                }
                            )
                        } else {
                            HHTipUtils.getInstance().showToast(baseContext, result.msg)
                        }
                    }
                    ScanTypeEnum.IDCARD_BACK -> {
                        ocrRequestParam.type = 5
                        val result = NetworkManager.init.userService().ocrIDCardBackRequest(ocrRequestParam)
                        LogUtils.i("识别结果", result.data)
                        if (result.isSuccess()) {
                            startActivity(
                                Intent(
                                    this@ChooseTypeActivity,
                                    OCRIDCardActivity::class.java
                                ).apply {
                                    putExtra("value", JsonUtils.gson.toJson(result.data))
                                }
                            )
                        } else {
                            HHTipUtils.getInstance().showToast(baseContext, result.msg)
                        }
                    }
                    else -> {
                        ocrRequestParam.type = 0
                    }
                }
                HHTipUtils.getInstance().dismissProgressDialog()
            }, {
                HHTipUtils.getInstance().showToast(baseContext, "识别异常,${it.message}")
            })
        }
    }
}